package com.cloud.adrian.novel.author.manager.chache;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.adrian.novel.author.dao.entity.AuthorInfo;
import com.cloud.adrian.novel.author.dao.mapper.AuthorInfoMapper;
import com.cloud.adrian.novel.author.novel.dto.AuthorInfoDto;
import com.cloud.adrian.novel.common.constant.CacheConstants;
import com.cloud.adrian.novel.common.constant.DatabaseConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 作家信息缓存管理
 * @Author: xiangguiliang
 * @version: 1.0
 * @since: 2024/05/29
 */
@Component
@RequiredArgsConstructor
public class AuthorInfoCacheManager {

    private final AuthorInfoMapper authorInfoMapper;

    /**
     * 查询作家缓存信息
     */
    @Cacheable(cacheManager = CacheConstants.REDIS_CACHE_MANAGER,
        value = CacheConstants.AUTHOR_INFO_CACHE_NAME, unless = "#result == null")
    public AuthorInfoDto getAuthor(Long userId) {
        QueryWrapper<AuthorInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(DatabaseConstants.AuthorInfoTable.COLUMN_USER_ID, userId)
                .last(DatabaseConstants.SqlEnum.LIMIT_1.getSql());
        AuthorInfo authorInfo = authorInfoMapper.selectOne(queryWrapper);
        if (Objects.isNull(authorInfo)) {
            return null;
        }
        return AuthorInfoDto.builder()
                .id(authorInfo.getId())
                .penName(authorInfo.getPenName())
                .status(authorInfo.getStatus()).build();
    }

    @CacheEvict(cacheManager = CacheConstants.REDIS_CACHE_PREFIX,
        value = CacheConstants.AUTHOR_INFO_CACHE_NAME)
    public void evictAuthorInfoCache() {
        // 调用此方法清除缓存
    }
}
